package com.ruoyi.event.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.vo.UserInfoVo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.service.UserDrugBusinessService;
import com.ruoyi.common.enums.UserBusinessSubType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.event.domain.EventZq;
import com.ruoyi.event.domain.bo.EventZqBo;
import com.ruoyi.event.domain.vo.EventZqVo;
import com.ruoyi.event.domain.vo.UserCurrentSjskZqVo;
import com.ruoyi.event.mapper.EventZqMapper;
import com.ruoyi.event.service.IEventZqService;
import com.ruoyi.user.enums.UserSjskTermType;
import com.ruoyi.user.enums.UserSjskType;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 人员转期Service业务层处理
 *
 * @author strongme
 * @date 2023-02-16
 */
@RequiredArgsConstructor
@Service
public class EventZqServiceImpl implements IEventZqService {

    private final EventZqMapper baseMapper;
    private final UserDrugBusinessService userDrugBusinessService;


    @Override
    public UserCurrentSjskZqVo getUserSjskZqInfo(Long sjskId) {
        UserInfoVo userInfoVo = userDrugBusinessService.queryById(sjskId);
        if (userInfoVo == null || !UserBusinessSubType.DRUG_SJSK.equals(userInfoVo.getSubType())) {
            return new UserCurrentSjskZqVo();
        }
        UserCurrentSjskZqVo vo = new UserCurrentSjskZqVo();
        vo.setJdrq(userInfoVo.getJdsj());
        String sjskType = userInfoVo.getType();
        String currentTerm = userInfoVo.getTermType();
        vo.setOriginTermType(currentTerm);
        Date jdsj = userInfoVo.getJdsj();
        long yearDiff = DateUtil.betweenYear(jdsj, new Date(), false);
        String targetTermType = currentTerm;
        if (yearDiff >= 3 && yearDiff < 6) {
            if (Objects.equals(UserSjskType.SJ.getUserType(), sjskType)) {
                targetTermType = UserSjskTermType.SJ_2.getUserType();
            } else {
                targetTermType = UserSjskTermType.SK_2.getUserType();
            }
        }
        if (yearDiff >= 6 && yearDiff < 9) {
            if (Objects.equals(UserSjskType.SJ.getUserType(), sjskType)) {
                targetTermType = UserSjskTermType.SJ_3.getUserType();
            } else {
                targetTermType = UserSjskTermType.SK_3.getUserType();
            }
        }
        vo.setTargetTermType(targetTermType);
        return vo;
    }

    /**
     * 查询人员转期
     */
    @Override
    public EventZqVo queryById(Long zqId) {
        return baseMapper.selectVoById(zqId);
    }

    /**
     * 查询人员转期列表
     */
    @Override
    public TableDataInfo<EventZqVo> queryPageList(EventZqBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EventZq> lqw = buildQueryWrapper(bo);
        Page<EventZqVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询人员转期列表
     */
    @Override
    public List<EventZqVo> queryList(EventZqBo bo) {
        LambdaQueryWrapper<EventZq> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EventZq> buildQueryWrapper(EventZqBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EventZq> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, EventZq::getUserId, bo.getUserId());
        lqw.eq(bo.getMemberId() != null, EventZq::getMemberId, bo.getMemberId());
        lqw.eq(StringUtils.isNotBlank(bo.getTargetTermType()), EventZq::getTargetTermType, bo.getTargetTermType());
        lqw.eq(StringUtils.isNotBlank(bo.getPreviousTermType()), EventZq::getPreviousTermType, bo.getPreviousTermType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), EventZq::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增人员转期
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(EventZqBo bo) {
        EventZq add = BeanUtil.toBean(bo, EventZq.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setZqId(add.getZqId());
        }
        updateSjskTermType(bo);
        return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateSjskTermType(EventZqBo bo) {
        if ("1".equals(bo.getStatus())) {
            // 审核通过，更新回sjsk
            UserInfoVo userInfoVo = userDrugBusinessService.queryById(bo.getUserId());
            if (userInfoVo != null) {
                userInfoVo.setTermType(bo.getTargetTermType());
                userDrugBusinessService.updateUserInfo(userInfoVo);
            }
        }
    }

    /**
     * 修改人员转期
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(EventZqBo bo) {
        EventZq update = BeanUtil.toBean(bo, EventZq.class);
        validEntityBeforeSave(update);
        updateSjskTermType(bo);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EventZq entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除人员转期
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
